package com.jokerku.mini.schedule.task;

import com.alibaba.fastjson.JSON;
import com.jokerku.mini.schedule.common.Constants;
import com.jokerku.mini.schedule.domain.ExecOrder;
import com.jokerku.mini.schedule.domain.ZkPath;
import com.jokerku.mini.schedule.service.HeartbeatService;
import com.jokerku.mini.schedule.service.ZkCuratorServer;
import com.jokerku.mini.schedule.sharding.ShardingService;
import org.apache.curator.framework.CuratorFramework;

import java.util.List;

/**
 * @Author: guzq
 * @CreateTime: 2023/06/02 00:40
 * @Description: 任务初始化
 * @Version: 1.0
 */
public class ScheduleExec {

    private static final ScheduleExec INSTANCE = new ScheduleExec();

    private ScheduleExec() {

    }

    public static ScheduleExec getInstance() {
        return INSTANCE;
    }

    public ScheduleExec initTask() {
        CronTaskRegister cronTaskRegister = Constants.Global.applicationContext.getBean("mini-schedule-cron-task-register", CronTaskRegister.class);

        for (List<ExecOrder> execOrderList : Constants.EXEC_ORDER_MAP.values()) {
            for (ExecOrder execOrder : execOrderList) {
                if (!execOrder.getAutoStartup()) continue;
                // 启动定时任务
                ScheduleRunnable scheduleRunnable = new ScheduleRunnable(execOrder.getBean(), execOrder);
                cronTaskRegister.addCornTask(scheduleRunnable, execOrder.getCron());
            }
        }
        return this;
    }

    public void initNode() throws Exception {
        for (List<ExecOrder> execOrderList : Constants.EXEC_ORDER_MAP.values()) {
            for (ExecOrder execOrder : execOrderList) {
                // 创建节点
                String pathRootServerIpClass = ZkPath.getServerTaskClassPath(execOrder);
                String pathRootServerIpClassMethod = ZkPath.getServerTaskClassMethodPath(execOrder);
                String pathRootServerIpClassMethodValue = ZkPath.getServerTaskClassMethodValuePath(execOrder);
                String pathRootServerIpClassMethodStatus = ZkPath.getServerTaskClassMethodStatusPath(execOrder);

                CuratorFramework client = Constants.Global.client;
                ZkCuratorServer.createNodeSimple(client, pathRootServerIpClass);
                ZkCuratorServer.createNodeSimple(client, pathRootServerIpClassMethod);
                ZkCuratorServer.createNodeSimple(client, pathRootServerIpClassMethodStatus);

                // 添加节点数据[临时]
                ZkCuratorServer.appendPersistentData(client, pathRootServerIpClassMethodValue, JSON.toJSONString(execOrder));
                // 添加节点数据[永久]
                ScheduledTask scheduledTask = Constants.SCHEDULED_TASK_MAP.get(execOrder.getTaskId());
                boolean startUp = null != scheduledTask && !scheduledTask.isCanceled();
                ZkCuratorServer.setData(client, pathRootServerIpClassMethodStatus, startUp ? "1" : "0");
            }
        }
    }
}
